package com.wontube.core.pub.servlet.handlers;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.wontube.core.pub.Scope;
import com.wontube.core.remote.IHandler;


/**
 * @author yuechao
 */
public class HandlerWrapper {
	private static Logger logger = LoggerFactory.getLogger(HandlerWrapper.class);
	
	private Class<IHandler> clazz;
	private Scope scope;

	private IHandler handler;

	public HandlerWrapper() {
	}

	public HandlerWrapper(Class<IHandler> clazz, Scope scope) throws InstantiationException, IllegalAccessException {
		this.clazz = clazz;
		this.scope = scope;

		if (this.scope == Scope.Singleton) {
			this.handler = this.clazz.newInstance();
		}
	}

	/**
	 * @return the clazz
	 */
	public Class<IHandler> getClazz() {
		return this.clazz;
	}

	/**
	 * @param clazz
	 *            the clazz to set
	 */
	public void setClazz(Class<IHandler> clazz) {
		this.clazz = clazz;
	}

	/**
	 * @return the scope
	 */
	public Scope getScope() {
		return scope;
	}

	/**
	 * @param scope
	 *            the scope to set
	 */
	public void setScope(Scope scope) {
		this.scope = scope;
	}

	/**
	 * 获得处理类的实例，考虑作用范围声明
	 * 
	 * @return
	 * @throws IllegalAccessException
	 * @throws InstantiationException
	 * 
	 */
	public IHandler getHandler() {
		try {
			if ((this.scope == Scope.Singleton && this.handler == null) || this.scope == Scope.Request) {
				this.handler = this.clazz.newInstance();
			}
		} catch (Exception e) {
			logger.error(e.toString());
		}

		return this.handler;
	}
}
